import Vue from 'vue'
import VueRouter from 'vue-router'
import MyLogin from '@/views/MyLogin'
import Layout from '@/views/Layout'
import MyHome from '@/views/MyHome'
import MyAsk from '@/views/MyAsk'
import MyVideo from '@/views/MyVideo'
import MyMine from '@/views/MyMine'
import edit from '@/views/MyMine/edit'
import MyArticle from '@/views/MyArticle'
import MySearch from '@/views/MySearch'
import MyResult from '@/views/MySearch/MyResult'
import MyChat from '@/views/MyMine/MyChat'
import MyInterest from '@/views/MyMine/MyInterest'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/layout/home' },
  { name: 'MyLogin', path: '/login', component: MyLogin },
  {
    name: 'Layout',
    path: '/layout',
    component: Layout,
    children: [
      {
        name: 'MyHome',
        path: 'home',
        component: MyHome,
        meta: {
          needKeep: true
        }
      },
      { name: 'MyAsk', path: 'ask', component: MyAsk },
      { name: 'MyVideo', path: 'video', component: MyVideo },
      {
        name: 'MyMine',
        path: 'mine',
        component: MyMine,
        meta: {
          needLogin: true
        }
      }
    ]
  },
  {
    name: 'edit',
    path: '/mine/edit',
    component: edit,
    meta: {
      needLogin: true
    }
  },
  { name: 'article', path: '/article', component: MyArticle },
  {
    name: 'search',
    path: '/search',
    component: MySearch,
    meta: {
      needKeep: true
    }
  },
  {
    name: 'result',
    path: '/search/result',
    component: MyResult,
    meta: {
      needKeep: true
    }
  },
  {
    name: 'chat',
    path: '/mine/chat',
    component: MyChat,
    meta: {
      needLogin: true
    }
  },
  {
    name: 'interest',
    path: '/mine/interest',
    component: MyInterest,
    meta: {
      needLogin: true
    }
  }
]

const router = new VueRouter({
  routes
})

import store from '@/store'
import { Toast } from 'vant'
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    if (store.state.tokenObj.token) {
      next()
    } else {
      Toast({
        message: '请先登录'
      })
      next({
        name: 'MyLogin',
        query: {
          back: to.path
        }
      })
    }
  } else {
    next()
  }
})
// 解决3.1版本后在控制台出现的警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
export default router
